package org.apache.dubbo.demo.config;

import java.util.concurrent.CompletableFuture;

public class A {

    public static void main(String[] args) {
        CompletableFuture<CompletableFuture<String>> future = CompletableFuture.completedFuture(providerAsyncMethod());
        try {
            CompletableFuture<String> serviceFuture = future.get();

            boolean isAsync = true;
            if (isAsync) {
                // this line will not block, but will return immediately with the result
                serviceFuture.whenComplete((r, e) -> {
                    System.out.println("Async result: " + r);
                    if (e != null) {
                        e.printStackTrace();
                    } else {
                        System.out.println(r);
                    }
                });
            } else {
                // this line will block until the result is available
                String result = serviceFuture.get();
                System.out.println(result);
            }
            System.out.println("Done");
            try {
                // wait for some long running task
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static CompletableFuture<String> providerAsyncMethod() {
        return CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(5000);
                System.out.println("service is called");
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            return "Hello World";
        });
    }

}
